import os
import padocr
import screenshot_adb
from ppadb.client import Client as AdbClient
import subprocess
import time
import coordinate
import smart_move

def connect_emulator():
    client = AdbClient(host="127.0.0.1", port=5037)
    client.remote_connect("127.0.0.1", 16384)  # 雷电默认端口
    return client


def adb_tap(x, y, device_serial=None):
    """完全解决多设备冲突的点击函数"""
    # 方法1：通过环境变量强制指定设备
    if device_serial:
        os.environ['ANDROID_SERIAL'] = device_serial

    # 方法2：使用绝对路径的adb命令
    adb_path = r"C:\platform-tools\adb.exe" # 可替换为你的adb完整路径，如 "C:\\platform-tools\\adb.exe"

    # 方法3：双重设备验证
    cmd = f"{adb_path} shell input tap {x} {y}"
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

    if result.returncode != 0:
        # 方法4：备用方案 - 使用adb -s 再次尝试
        if device_serial:
            cmd = f"{adb_path} -s {device_serial} shell input tap {x} {y}"
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
            if result.returncode == 0:
                return True

        print(f"点击失败: {result.stderr.strip()}")
        return False
    return True


def adb_tap_with_delay(coords=None, x=None, y=None, delay_sec=0.5, device_serial=None):
    """完全兼容的带延迟点击"""
    # 参数处理
    if x is not None and y is not None:
        target_x, target_y = x, y
    elif coords is not None and isinstance(coords, (tuple, list)) and len(coords) == 2:
        target_x, target_y = coords
    else:
        raise ValueError("坐标格式错误！请使用 (x,y) 或 x=100,y=200 格式")

    # 执行点击
    if adb_tap(target_x, target_y, device_serial):
        time.sleep(delay_sec)
        return True
    return False


def adb_multi_tap(coordinates, interval=0.1, device_serial=None):
    """连续点击多个坐标"""
    for x, y in coordinates:
        if not adb_tap(x, y, device_serial):
            return False
        time.sleep(interval)
    return True


def adb_swipe(start_x, start_y, end_x, end_y, duration_ms=300, device_serial=None):
    """滑动操作"""
    cmd = f"adb shell input swipe {start_x} {start_y} {end_x} {end_y} {duration_ms}"
    if device_serial:
        cmd = f"adb -s {device_serial} shell input swipe {start_x} {start_y} {end_x} {end_y} {duration_ms}"
    subprocess.run(cmd, shell=True)


def safe_adb_tap(x, y, max_retry=3, device_serial=None):
    """带重试机制的点击"""
    for attempt in range(max_retry):
        if adb_tap(x, y, device_serial):
            return True
        print(f"点击失败，第{attempt + 1}次重试...")
        time.sleep(1)
    return False


# 完整工作流程示例
def click_target_image(image_path, confidence=0.8, max_retry=3, device_serial=None):
    for _ in range(max_retry):
        target_pos = screenshot_adb.find_image_on_screen_adb(image_path, confidence, device_serial=device_serial)
        if target_pos:
            if safe_adb_tap(*target_pos, device_serial=device_serial):
                print(f"点击成功！{target_pos}")
                return True
        time.sleep(1)
    print("操作失败")
    return False


def go_home(device_serial=None):
    img = r"E:\DESKTOP\img\huichengshi.bmp"
    click_target_image(img, device_serial=device_serial)


def go_shen_long(device_serial=None):
    img1 = r"img\xiaomishu.bmp"
    img2 = r"img\teshuchuansong.bmp"
    img3 = r"img\shenlongshendi.bmp"
    img4 = r"img\2wjinru.bmp"
    img5 = r"img\guaji.bmp"
    click_target_image(img1, device_serial=device_serial)  # 点击神龙的圣地
    click_target_image(img2, device_serial=device_serial)  # 点击神龙的圣地
    click_target_image(img3, device_serial=device_serial)  # 点击神龙的圣地
    click_target_image(img4, device_serial=device_serial)  # 点击神龙的圣地
    click_target_image(img5, device_serial=device_serial)  # 点击神龙的圣地


def get_bmp_files(folder_path):
    bmp_files = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".bmp"):
                bmp_files.append(os.path.join(root, file))
    return bmp_files


def close_all(device_serial=None):
    """关闭所有出现的对话框"""
    close_bmp = get_bmp_files(r"E:\DESKTOP\img\close")  # 获取需要点击的文件夹物品
    img = screenshot_adb.fast_screenshot(device_serial=device_serial)  # 截图
    mengzhong_tag = screenshot_adb.find_image_on_screen_adb(r"img\mengzhong.bmp", device_serial=device_serial)
    for close_bmp_file in close_bmp:
        res = screenshot_adb.find_image_on_screen_adb_not_shot(img=img, target_image_path=close_bmp_file)

        if close_bmp_file == r"E:\DESKTOP\img\mengzhong.bmp":
            if mengzhong_tag:
                continue
            else:
                adb_tap_with_delay(res, device_serial=device_serial)

        elif res:

            adb_tap_with_delay(res, device_serial=device_serial)


def attack_empty(devices_serial=None):
    """发现敌人并攻击"""
    empty_tag = screenshot_adb.find_image_on_screen_adb(r"img\empty.bmp", device_serial=devices_serial)

    if empty_tag:
        while True:
            emptys = padocr.get_empty_name(device_serial=devices_serial)
            mengzhong_tag = screenshot_adb.find_image_on_screen_adb(r"img\mengzhong.bmp",
                                                                     device_serial=devices_serial)

            if mengzhong_tag:
                break
            elif not emptys:
                break
            else:
                for empty in coordinate.avoid_empty:
                    if empty in emptys:
                        go_home(device_serial=devices_serial)
                        break
                adb_tap_with_delay(empty_tag, device_serial=devices_serial)
                adb_tap_with_delay(coordinate.coord['攻击'], delay_sec=0.1, device_serial=devices_serial)
                adb_tap_with_delay(coordinate.coord['攻击'], delay_sec=0.1, device_serial=devices_serial)
                print(f'报告发现敌人{emptys}')


def use_item(devices_serial = None):

    adb_tap_with_delay(coordinate.coord['背包'],device_serial=devices_serial)  # 打开物品
    click_target_image(r"E:\DESKTOP\img\recycle.bmp", device_serial=devices_serial)  # 点击回收
    time.sleep(0.5)
    adb_tap_with_delay(coordinate.coord['一键回收'],device_serial=devices_serial)  # 打开物品

    item_png = get_bmp_files('img/use_items')  # 获取文件夹所有可以使用物品

    for item in item_png:  # 遍历所需要使用的物品
        res = screenshot_adb.find_all_image_on_screen_adb(item, confidence=0.95, device_serial=devices_serial)  # 返回查找结果
        # res = remove_close_duplicates(res, 2)  # 结果去重
        # 使用物品
        # print(f'查找{item}')
        if res:
            # print(f'找到{item}的坐标{res}')
            if item == r"E:\DESKTOP\img\use_items\gold-ingot.bmp":
                print(f'本次收获元宝{len(res)*5000}')
            for i in res:
                adb_tap(i[0],i[1], device_serial=devices_serial)
                time.sleep(0.1)
                adb_tap(i[0],i[1], device_serial=devices_serial)
                time.sleep(0.5)

    time.sleep(0.5)
    click_target_image(r"E:\DESKTOP\img\tidy.bmp", device_serial=devices_serial)  # 点击整理
    time.sleep(2)
    for item in item_png:  # 遍历所需要使用的物品
        res = screenshot_adb.find_all_image_on_screen_adb(item, confidence=0.95, device_serial=devices_serial)  # 返回查找结果
        # 使用物品
        # res = remove_close_duplicates(res, 2)  # 结果去重

        if res:
            for i in res:
                adb_tap(i[0],i[1], device_serial=devices_serial)
                time.sleep(0.1)
                adb_tap(i[0],i[1], device_serial=devices_serial)
                time.sleep(0.5)
    close_all(devices_serial=devices_serial)

    time.sleep(0.5)
    close_all(devices_serial=devices_serial)


def every_two_hours_use_item(devices_serial = None):
    current_time = time.localtime()
    if current_time.tm_hour % 2 == 0  and current_time.tm_min == 30:
        use_item(devices_serial=devices_serial)


def mengzhong(device_serial=None):  # 将device_device改为device_serial
    mengzhong_tag = screenshot_adb.find_image_on_screen_adb(r"img\mengzhong.bmp", device_serial=device_serial)
    return mengzhong_tag


def open_rage(device_serial= None):
    rage_img = r"E:\DESKTOP\img\rage-can-go.bmp"
    rage_tag = screenshot_adb.find_image_on_screen_adb(rage_img, device_serial=device_serial)
    if rage_tag:
        close_all(devices_serial=device_serial)
        smart_move.move_to_target((339, 330))
        click_target_image(r"E:\DESKTOP\img\rage.bmp", device_serial=device_serial)
        adb_tap_with_delay(coordinate.coord['开启狂暴之力'], device_serial=device_serial)
        close_all(devices_serial=device_serial)

def click_gua_ji(device_serial = None):
    time.sleep(0.5)
    click_target_image(r'img/guaji.bmp', device_serial=device_serial)

def auto_monster(device_serial = None):
    monster_tag = padocr.detect_red_with_stats(device_serial=device_serial)
    mengzhong_tag = mengzhong(device_serial=device_serial)

    while True:
        mengzhong_tag = mengzhong(device_serial=device_serial)
        if mengzhong_tag:
            break
        time.sleep(3)
        close_all(device_serial=device_serial)
        monster_tag = padocr.detect_red_with_stats(device_serial=device_serial)
        if monster_tag['farthest_point']:
            direction = smart_move.calculate_direction((101, 79), monster_tag['farthest_point'])
            smart_move.swipe_run(direction)
        far_master, close_monster = Find_Pic.find_and_process_targets()
        # print(far_master)
        # 判断是否有怪
        if len(close_monster) < 7:

            if far_master:
                click_monster(far_master[0][0], far_master[0][1] + 46)
                close_monster_tag = 0

        click_zidong()
        current_coodr = re_number.get_current_coordinate()
        if current_coodr != start_coodr:
            close_monster_tag += 1
            print(f'第{close_monster_tag}没有发现怪物')
            start_coodr = current_coodr
        else:
            close_monster_tag =0
        if close_monster_tag > monster_num:
            break

# 使用示例
if __name__ == "__main__":

    client = connect_emulator()
    devices = client.devices()

    if not devices:
        print("没有找到连接的设备")
        exit()

    # 打印所有设备信息
    print("可用设备:")
    for i, device in enumerate(devices):
        print(f"{i}: {device.serial}")

    # 自动选择第一个设备（或让用户选择）
    selected_device = devices[0]
    print(f"\n选择设备: {selected_device.serial}")
    open_rage(device_serial=selected_device.serial)
    # use_item(devices_serial=selected_device.serial)
    # img = r'img/recycle.bmp'
    # res  = screenshot_adb.find_image_on_screen_adb(img,show_result=True, device_serial=selected_device.serial, confidence=0.5)
    # print(res)
    # adb_tap_with_delay(922, 228, device_serial=selected_device.serial)


